
package ija.net;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;



/**
 * Trida se stara o zasilani zprav po siti. Pro kazde zaslani vytvori nove 
 * spojeni na libovolnem portu. Cilova adresa a port je zadana pri inicializaci
 * a jiz se nemeni.
 * @author Radek Necas, xnecas18
 */
public class Client {

    protected int port;
    protected InetAddress host;
    
    
    /**
     * Konstruktor vytvori noveho klienta
     * @param ip cilova adresa, kam se budou zasilat data
     * @param port cilovy port, na ktery se budou zasilat data
     */
    public Client(InetAddress ip, int port) {
        this.host = ip;
        this.port = port;
    }
    
    /**
     * Konstruktor vytvori noveho klienta
     * @param ip cilova adresa (ip nebo hostname), kam se budou zasilat data
     * @param port cilovy port, na ktery se budou zasilat data
     */
    public Client(String hostname, int port) throws UnknownHostException {
        this(InetAddress.getByName(hostname), port);
    }
    
    
    
    /**
     * Metoda zasle zpravu na stanici urcenou v konstruktoru
     * @param msg zasilana zprava
     * @throws IOException
     * @throws UnknownHostException 
     */
    public void send (Message msg) throws IOException, UnknownHostException {
    
        Socket echoSocket = null;
        ObjectOutputStream outObj = null;
  
        try {
            echoSocket = new Socket(host, port);
            outObj = new ObjectOutputStream(echoSocket.getOutputStream());
            outObj.writeObject(msg);
        } finally {
            if(outObj != null)
                outObj.close();
            if(echoSocket != null)
                echoSocket.close();
        }
    }
}
